/**
 * Created by Johnny on 2017/2/8.
 */
var PortalIndex = function() {

    var ai = this;
    var url_rest_grantedmenu = apiloc+'/v1/user/portalMenu';
    var helploc = resloc + '/static/html/help/platform/portal/'+lang+'/index.html';

    var initPage = function () {
        setTimeout(function () {
            $('.index-page-title').show('fold');
        },1);

        window.listenerOfChildWindow = {
            "listeners" : {},
            "trigger" : function (listener, args) {
                if (typeof(window.listenerOfChildWindow.listeners[listener])=='function') {
                    setTimeout(function () {
                        window.listenerOfChildWindow.listeners[listener](args);
                    }, 1);
                }
            },
            "register" : function (listenerName, listenerFunc) {
                if (typeof(listenerFunc)=='function') {
                    window.listenerOfChildWindow.listeners[listenerName] = listenerFunc;
                }
            }
        };

        $('.global-help-link').attr('href', helploc);

        window.onSessionTimeout = function() {
            alertWarn(i18nindex.msg_sessiontimeout, null, function() {
                window.top.location.href='/';
            });
            $('.sweet-overlay').css('background-color', '#eeeeee');
        };

    };

    //init menu and avatar
    var loadGrantedMenus = function() {
        doGetAsyncJson(url_rest_grantedmenu, function(ret) {
            if (!ret) {
                msgErr(i18nindex.msg_readerr); return;
            } else {
                renderGrantedMenu(ret.portalMenus);
                if (ret.isAdmin) {
                    $("#accountDropNav").prepend('<li>'+
                        '<a class="" href="/admin" target="_blank">'+
                        '<i class="icon-screen-desktop"></i> '+i18nindex.adminconsole+
                        '</a></li>');
                }
                if (ret.avatarEnabled) {
                    window.avatarEnabled = ret.avatarEnabled;  //for avatar
                    window.avatarOssUrlPrefix = ret.avatarOssUrlPrefix;  //for avatar
                    var avatarUrl = window.avatarOssUrlPrefix + encodeURIComponent(base64encode(ret.loginName)) + '.'+avatarExt;
                    /*var avatarImg = $('.top-menu .header-avatar');
                    var onerrorUrl = avatarImg.attr('onerror-url');
                    avatarImg.error(function(){
                        $(this).attr('src', onerrorUrl);
                    }).attr('src', avatarUrl);*/
                    $('.top-menu .header-avatar').attr('src', avatarUrl);
                }
            }
        });
    };

    //load menu data
    var renderGrantedMenu = function(data) {

        var menustr = '';
        for (var i in data) {
            var haschildren = data[i].children && data[i].children.length;

            var str1 = '<li>'+
                '<a resid="'+data[i].id+'" label="'+data[i].name+'"'+
                (data[i].resUri ? ' href="'+menuUri(data[i].resUri, data[i].resType)+'"' : ' href="javascript:void(0);"') +
                ' class="'+menuCls(data[i].resUri)+'"'+
                getPageId(data[i].resUri, data[i].resType)+
                '>'+
                '<i class="'+data[i].icon+'"></i>'+
                '<span class="title">'+data[i].name+'</span>'+
                '<span class="selected"></span>'+
                (haschildren ? '<span class="arrow"></span>' : '')+
                '</a>';
            if (haschildren) {
                str1 += '<ul class="sub-menu" style="display: none;">';
                var childrenstr = getChildMenuStr(data[i].children);
                str1 += childrenstr;
                str1 += '</ul>';
            }
            str1 += '</li>';
            menustr += str1;
        }
        //console.log(menustr);
        menustr && $("#portalmenu").append(menustr);
    };

    var getChildMenuStr = function(data) {
        var menustr = '';
        for (var i in data) {
            var haschildren = data[i].children && data[i].children.length;
            if (data[i].resType=='elem') {
                var str1 = '<span style="display: none">'+JSON.stringify(data[i])+'</span>';
            } else {
                var str1 = '<li>'+
                    '<a resid="'+data[i].id+'" label="'+data[i].name+'"'+
                    (data[i].resUri ? ' href="'+menuUri(data[i].resUri, data[i].resType)+'"' : ' href="javascript:void(0);"') +
                    ' class="'+menuCls(data[i].resUri)+'"'+
                    getPageId(data[i].resUri, data[i].resType)+
                    '>'+
                    '<span class=""><i class="'+data[i].icon+'"></i>&nbsp;&nbsp;'+data[i].name+'</span>'+
                    (haschildren ? '<span class="arrow"></span>' : '')+
                    '</a>';
            }
            if (haschildren) {
                str1 += '<ul class="sub-menu" style="display: none;">';
                var childrenstr = getChildMenuStr(data[i].children);
                str1 += childrenstr;
                str1 += '</ul>';
            }
            str1 += '</li>';
            menustr += str1;
        }
        return menustr;
    };

    function menuCls(resUri) {
        var cls = '';
        if (resUri && typeof resUri == 'string') {
            if (resUri.indexOf("ajaxify:")>=0) {
                cls = "ajaxify";
            } else {
                cls = "framify";
            }

        } else if (resUri && typeof resUri == 'object') {
            cls = "ajaxify";
        }
        return cls;
    }

    //uri is diff from admin
    function menuUri(resUri, resType) {
        if (typeof resUri == 'object') {
            if (resType=='bdm') {
                return '/admin/topage?path=layout/config/bdm&bdmIdEnc='+resUri.bdmIdEnc;
            }
        }
        return resUri;
    }

    function getPageId(resUri, resType, resId) {
        if (resUri) {
            if (typeof resUri == 'object' && resType=='bdm') {
                return ' pageid="layout_admin_cfg_bdmpage_'+resUri.bdmIdEnc+'"';
            }
            return ' pageid="'+resId+'"';
        }
        return "";
    }

    return {
        init: function () {
            window.oncontextmenu = function() {
                return false;
            }
            loadGrantedMenus();
            initPage();
        }
    }

}();


// generate a jstree
function initJsTree(jqSelector, source, options, events, dataFilter) {
    var control = $(jqSelector);
    control.data('jstree', false);//clean

    var _options = {
        'core': {
            "themes": {
                "responsive": false
            }
        }
    };
    if (options) $.extend(_options, options);
    if (events) {
        for (var e in events) {
            typeof(events[e])=='function' && control.on(e, events[e]);
        }
    }

    if (typeof(source)=='function') {
        var data = source();
        _options.core.data = typeof(dataFilter)=='function' ? dataFilter(data) : data;
        control.jstree(_options);
    } else if (typeof(source)=='string') {
        doGetAsyncJson(source, function (data) {
            _options.core.data = typeof(dataFilter)=='function' ? dataFilter(data) : data;
            control.jstree(_options);
        });
    } else {
        _options.core.data = typeof(dataFilter)=='function' ? dataFilter(source) : source;
        control.jstree(_options);
    }

    return control.jstree(true);
}

var CommonUtil = function() {

    var cmu = this;
    var url_rest_getallorgs = apiloc + '/v1/fa/orgs/allByTenant?timezoneOffset='+new Date().getTimezoneOffset();
    var url_rest_getallorgusers = apiloc + '/v1/fa/org/';
    var url_rest_getallroles = apiloc + '/v1/fa/role/query?timezoneOffset='+new Date().getTimezoneOffset();
    var icon_path_orgtree = resloc + "/static/skins/lightblue/images/platform/fa/";

    this.selectOrg = function(rootOrg, curSels, multi, callback) {
        var editModal = bootbox.dialog({
            title : i18nindex.orgsel,
            message : '<div style="height:500px;">' +
            '<div class="row">'+
            '<div class="selector-tree-org col-md-12" style="height:500px;">' +
            '</div>'+
            '</div>'+
            '</div>',
            onEscape : true,
            buttons : {
                ok: {
                    label: i18nindex.ok,
                    className: 'btn-success',
                    callback : function() {
                        //console.log('save');
                        Metronic.startPageLoading();
                        var sels = cmu.orgtree.get_selected(true);
                        var res = [];
                        for (var i in sels) {
                            if (sels[i].id!='ROOT') {
                                res.push({orgId:sels[i].id, orgName:sels[i].text, fullName:cmu.getOrgFullName(cmu.orgtree, sels[i].id, sels[i].text)});
                            }
                        }
                        editModal.modal('hide');
                        Metronic.stopPageLoading();
                        callback(res);
                    }
                },
                cancel: {
                    label: i18nindex.cancel,
                    className: 'btn-default',
                    callback : function() {
                        editModal.modal('hide');
                    }
                }
            }
        }).on('shown.bs.modal', function() {
            Metronic.startPageLoading();
            //init org tree
            doGetAsyncJson(url_rest_getallorgs,
                function(ret) {
                    if (ret) {
                        cmu.orgtree = initJsTree(editModal.find('.selector-tree-org'),
                            ret,
                            {
                                'core': {
                                    "multiple": !!multi
                                },
                                'plugins' : ["checkbox", 'types', 'unique', 'search'],
                                "themes" : { "stripes" : true },
                                'types' : {
                                    '00' : {
                                        icon : icon_path_orgtree + 'orgAll.png'
                                    },
                                    "10" : {
                                        icon : icon_path_orgtree + 'orgCompany.png'
                                    },
                                    "20" : {
                                        icon : icon_path_orgtree + 'orgDept.png'
                                    }
                                },
                                "checkbox" : {
                                    three_state : false,
                                    cascade : "undetermined"
                                }
                            },
                            {
                                'ready.jstree' : function(e, data) {
                                    if (curSels && curSels.length) {
                                        for (var i in curSels) {
                                            data.instance.select_node(curSels[i]);
                                        }
                                    }
                                }
                            },
                            cmu.filterOrgTreeData);
                    } else {
                        cmu.onError();
                    }
                    Metronic.stopPageLoading();
                },
                cmu.onError);
        });
    }

    this.selectUser = function(rootOrg, curSels, multi, callback) {
        var modalBody;
        if (multi) {
            modalBody = '<div style="height:500px;">' +
                '<div class="row">'+
                '<div class="selector-user-tree-org col-md-4" style="height:500px;overflow: scroll;">' +
                '</div>'+
                '<div class="col-md-8" style="height:500px;">' +
                '<table class="selector-user-grid"></table>'+
                '</div>'+
                '</div>'+
                '</div>';
        } else {
            modalBody = '<div style="height:500px;">' +
                '<div class="row">'+
                '<div class="selector-user-tree-org col-md-4" style="height:500px;overflow: scroll;">' +
                '</div>'+
                '<div class="col-md-8" style="height:500px;">' +
                '<table class="selector-user-grid"></table>'+
                '</div>'+
                '</div>'+
                '</div>';
        }
        var editModal = bootbox.dialog({
            title : i18nindex.usersel,
            size: 'large',
            message : modalBody,
            onEscape : true,
            buttons : {
                ok: {
                    label: i18nindex.ok,
                    className: 'btn-success',
                    callback : function() {
                        //console.log('save');
                        var sels = editModal.griduser.bootstrapTable('getSelections');
                        var res = [];
                        for (var i in sels) {
                            res.push({userId:sels[i].USER_ID,loginName:sels[i].LOGIN_NAME,displayName:sels[i].DISPLAY_NAME});
                        }
                        editModal.modal('hide');
                        callback(res);
                    }
                },
                cancel: {
                    label: i18nindex.cancel,
                    className: 'btn-default',
                    callback : function() {
                        editModal.modal('hide');
                    }
                }
            }
        }).on('shown.bs.modal', function() {
            Metronic.startPageLoading();
            //init org tree
            doGetAsyncJson(url_rest_getallorgs,
                function(ret) {
                    if (ret) {
                        cmu.orgtree4userselect = initJsTree(editModal.find('.selector-user-tree-org'),
                            ret,
                            {
                                'core': {
                                    "multiple": true
                                },
                                'plugins' : ['types', 'unique', 'search'],
                                "themes" : { "stripes" : true },
                                'types' : {
                                    '00' : {
                                        icon : icon_path_orgtree + 'orgAll.png'
                                    },
                                    "10" : {
                                        icon : icon_path_orgtree + 'orgCompany.png'
                                    },
                                    "20" : {
                                        icon : icon_path_orgtree + 'orgDept.png'
                                    }
                                }
                            },
                            {
                                'ready.jstree' : function(e, data) {

                                },
                                'changed.jstree': function(node, action, selected, event) {
                                    // console.log(node);
                                    // console.log(action);
                                    // console.log(selected);
                                    // console.log(event);
                                    if (typeof(action)=='string' || !action.node) return;
                                    if (action.node.id!='ROOT') {
                                        editModal.griduser.bootstrapTable('refreshOptions', {url : url_rest_getallorgusers+action.node.id+'/users'});
                                    }
                                }
                            },
                            cmu.filterOrgTreeData);
                    } else {
                        cmu.onError();
                    }
                    Metronic.stopPageLoading();
                },
                cmu.onError);

            //init uesrgrid
            editModal.griduser = editModal.find('.selector-user-grid').bootstrapTable('destroy').bootstrapTable({
                method: 'get',
                cache: false,
                dataType:"json",
                complete: fm_checkSession,
                idField: "loginName",//标识哪个字段为id主键
                'data-locale': lang_dp,
                showToggle: false,//名片格式
                cardView: false,//设置为True时显示名片（card）布局
                clickToSelect: true,//点击行即可选中单选/复选框
                queryParamsType: "limit", //参数格式,发送标准的RESTFul类型的参数请求
                pagination: true,
                sidePagination: 'server',
                silentSort: false,
                uniqueId: 'loginName',
                columns: [{
                    radio : true
                }, {
                    field: 'USER_ID',
                    align: "center",
                    width: 100,
                    title: 'USER_ID',
                    visible: false
                },{
                    field: 'DISPLAY_NAME',
                    align: "center",
                    //sortable: true,
                    width: 150,
                    title: i18nindex.displayName
                },{
                    field: 'EMAIL',
                    align: "center",
                    //sortable: true,
                    width: 150,
                    title: i18nindex.email
                },{
                    field: 'USER_TYPE',
                    align: "center",
                    title: i18nindex.userType,
                    width: 60,
                    formatter : function(val, row, idx) {
                        return i18nindex.enu_userType[row['USER_TYPE']];
                    }
                }, {
                    field: 'STATUS',
                    align: "center",
                    title: i18nindex.userStatus,
                    width: 30,
                    formatter : function(val, row, idx) {
                        return i18nindex.enu_userStatus[row['STATUS']];
                    }
                }, {
                    field: 'GENDER',
                    align: "center",
                    //sortable: true,
                    width: 30,
                    title: i18nindex.gender,
                    formatter : function(val, row, idx) {
                        return i18nindex.enu_gender[val];
                    }
                }],
                formatNoMatches:function(){//没有匹配的结果
                    return i18nindex.norecord;
                }
            }).bind('dbl-click-row.bs.table', function(e, row, $element) {
                editModal.modal('hide');
                callback([{userId:row.USER_ID,loginName:row.LOGIN_NAME,displayName:row.DISPLAY_NAME}]);
            });
        });
    }

    this.selectRole = function(rootOrg, curSels, roleType, multi, callback) {
        var modalBody = '<div style="height:500px;">' +
            '<div class="row">'+
            '<div class="col-md-12" style="height:500px;">' +
            '<table class="selector-role-grid table-condensed"></table>'+
            '</div>'+
            '</div>'+
            '</div>';
        var editModal = bootbox.dialog({
            title : i18nindex.rolesel,
            size: 'large',
            message : modalBody,
            onEscape : true,
            buttons : {
                ok: {
                    label: i18nindex.ok,
                    className: 'btn-success',
                    callback : function() {
                        //console.log('save');
                        var sels = editModal.gridrole.bootstrapTable('getSelections');
                        var res = [];
                        for (var i in sels) {
                            res.push({roleId:sels[i].roleId,roleName:sels[i].roleName,roleDesc:sels[i].roleDesc});
                        }
                        editModal.modal('hide');
                        callback(res);
                    }
                },
                cancel: {
                    label: i18nindex.cancel,
                    className: 'btn-default',
                    callback : function() {
                        editModal.modal('hide');
                    }
                }
            }
        }).on('shown.bs.modal', function() {
            Metronic.startPageLoading();
            //init uesrgrid
            editModal.gridrole = editModal.find('.selector-role-grid').bootstrapTable('destroy').bootstrapTable({
                method: 'get',
                cache: false,
                dataType:"json",
                complete: fm_checkSession,
                idField: "loginName",//标识哪个字段为id主键
                'data-locale': lang_dp,
                showToggle: false,//名片格式
                cardView: false,//设置为True时显示名片（card）布局
                clickToSelect: true,//点击行即可选中单选/复选框
                singleSelect: false,
                queryParamsType: "limit", //参数格式,发送标准的RESTFul类型的参数请求
                url: url_rest_getallroles + '&roleType='+roleType,
                search: true,
                pagination: true,
                sidePagination: 'server',
                silentSort: false,
                uniqueId: 'loginName',
                columns: [{
                    width: '3%',
                    checkbox: true
                }, {
                    field: '_ITEM_NO',
                    align: "center",
                    width: '5%',
                    title: i18nindex.seq
                },{
                    field: 'ROLE_NAME',
                    align: "center",
                    sortable: true,
                    width: '15%',
                    title: i18nindex.displayName,
                    formatter : function(val, row, idx) {
                        return row['roleName'];
                    }
                }, {
                    field: 'ROLE_DESC',
                    align: "center",
                    sortable: true,
                    width: '20%',
                    title: i18nindex.desc,
                    formatter : function(val, row, idx) {
                        return row['roleDesc'];
                    }
                }, {
                    field: 'CREATOR',
                    align: "center",
                    sortable: true,
                    width: '15%',
                    title: i18nindex.creator,
                    formatter : function(val, row, idx) {
                        return row['creator'];
                    }
                }, {
                    field: 'CREATE_TIME',
                    align: "center",
                    sortable: true,
                    width: '15%',
                    title: i18nindex.createTime,
                    formatter : function(val, row, idx) {
                        return row['createTime'];
                    }
                }],
                formatNoMatches:function(){//没有匹配的结果
                    return i18nindex.norecord;
                }
            }).bind('dbl-click-row.bs.table', function(e, row, $element) {
                editModal.modal('hide');
                callback([{roleId:row.roleId,roleName:row.roleName,roleDesc:row.roleDesc}]);
            });
            Metronic.stopPageLoading();
        });
    }

    this.onError = function() {
        msgErr(i18nindex.msg_commiterr);
        Metronic.stopPageLoading();
    }

    this.filterOrgTreeData = function(data) {
        // console.log(data);
        if ($.isArray(data)) {
            for (var i in data) {
                data[i].li_attr = {'orgType':data[i].type,
                    'creatorName':data[i].creatorName,
                    'createTime':data[i].createTime,
                    'orgDesc':data[i].desc,
                    'parent' : data[i].parent
                };
            }
        } else{
            data = [];
        }
        data.unshift({
            'id': 'ROOT',
            "parent" : "#",
            'text': i18nindex.allorg,
            'type': '00',
            'state': {
                'opened': true
            }
        });
        return data;
    };

    this.getOrgFullName = function(tree, nodeId, fn) {
        var parentId = tree.get_parent(nodeId);
        if (parentId && parentId!='ROOT') {
            var pnode = tree.get_node(parentId);
            fn = pnode.text + '/' + fn;
            fn = cmu.getOrgFullName(tree, parentId, fn);
        }
        return fn;
    }

};
